/**
 * Created by wry on 2015/4/13.
 */
var activityService = require('../../services/backoffice/backOffice-activityService');
var messageUtil = require('../../common/utils/messageUtil');
var toolUtil = require('../../common/utils/toolUtil');
var nodeExcel = require('excel-export');

exports.getBackOfficeActivityList = function (req, res) {
    var communityId = req.params.communityId;
    var page = req.params.page;
    var level = req.params.level;
    var desc = req.params.desc;

    activityService.getBackOfficeActivityListService(communityId, page,level, desc, function (err, result) {
        if (err) {
            logger.error('Exception happened when getBackOfficeActivityList...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when getBackOfficeActivityList...!' + err.message));
        } else {
            var data = {
                aList: result[0],
                totalPage: result[1]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    });
};

exports.getBackOfficeActivityByFilter = function (req, res) {

    var input = req.body;

    activityService.getBackOfficeActivityByFilterService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when getBackOfficeActivityList...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when getBackOfficeActivityList...!' + err.message));
        } else {
            //logger.debug(result);
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    });
};



exports.moveActivityToTop = function (req, res) {
    var input = req.body;

    activityService.moveActivityToTopService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when moveActivityToTopService...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when moveActivityToTopService...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.cancelTopActivity = function (req, res) {
    var input = req.body;

    activityService.cancelTopActivityService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when cancelTopActivity...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when cancelTopActivity...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.moveAllToTop = function (req, res) {
    var input = req.body;

    activityService.moveAllToTopService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when moveAllToTop...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when moveAllToTop...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.cancelTopAll = function (req, res) {
    var input = req.body;

    activityService.cancelTopAllService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when cancelTopAllService...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when cancelTopActivity...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.getAllUgc = function (req, res) {
    var page = req.params.page;
    var communityId = req.params.communityId;

    activityService.getAllUgcService(page, communityId, function (err, result) {
        if (err) {
            logger.error('Exception happened when getAllUgc...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when getAllUgc...!' + err.message));
        } else {

            var data = {
                totalPage: Math.ceil(result[1] / 20),
                allList: result[0]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    })
};

exports.backOfficeUpdateActivity = function (req, res) {
    var input = req.body;

    activityService.backOfficeUpdateActivityService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when backOfficeUpdateActivity...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when backOfficeUpdateActivity...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));

            if (input.tag != null) {
                toolUtil.putMessageQAMQ({
                    msgType: 'hobby',
                    questionId: input._id + '',
                    contentType: 'activity'
                });
            }
        }
    })
};

exports.backOfficeUpdateActivityServiceByModerator = function (req, res) {
    var input = req.body;

    activityService.backOfficeUpdateActivityServiceByModerator(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when backOfficeUpdateActivity...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when backOfficeUpdateActivity...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));

            if (input.tag != null) {
                toolUtil.putMessageQAMQ({
                    msgType: 'hobby',
                    questionId: input._id + '',
                    contentType: 'activity'
                });
            }
        }
    })
};

exports.reports = function (req, res) {
    var input = req.body;

    activityService.reports(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when reports...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when reports...!' + err.message));
        } else {
            logger.info("reports: " + JSON.stringify(result));
            var data = [], itemData = {};
            for (var i = 0; i < result.length; i++) {
                itemData = {
                    nickName: result[i].reportUser.nickName ? result[i].reportUser.nickName : "",
                    desc: result[i].question ? result[i].question.desc : ""
                }
                data.push(itemData);
            }
            res.json(messageUtil.composeSucceededMessage(req, null, data));
            //logger.info("reports: "+JSON.stringify(result));
        }
    })
};

exports.changeActivityLevel = function (req, res) {
    var input = req.body;

    activityService.changeActivityLevelService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when changeActivityLevelService...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            if(input.level == 1) {
                //个推
                var content = {
                    type: 1,
                    flag: 2,
                    openType: input.openType,
                    contentId: input.activityId,
                    createdBy: input.userId,
                    desc: input.desc
                };
                var pushData = {
                    uList: [input.userId],
                    content: content,
                    ip: req.headers['X-Real-IP'],
                    tag: input.tag,
                    type: 'operate'
                };
                logger.debug(pushData);
                toolUtil.putMessageGetuiPushMQ(pushData);

            }
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.moveTopById = function (req, res) {
    var input = req.body;

    activityService.moveTopByIdService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when moveAllToTop...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when moveAllToTop...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};

exports.cancelTopById = function (req, res) {
    var input = req.body;

    activityService.cancelTopByIdService(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when cancelTopAllService...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when cancelTopActivity...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    })
};



exports.exportJoinActivity = function (req, res) {

    activityService.exportJoinActivityService(req, function (err, result) {
        if (err) {
            logger.error('Exception happened when exportJoinActivity...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when exportJoinActivity...!' + err.message));
        } else {
            var data = result[0];
            var conf = {};

            conf.cols = [{
                caption: '小区',
                type: 'String'
            }, {
                caption: '活动标题',
                type: 'String'
            }, {
                caption: '姓名',
                type: 'String'
            }, {
                caption: '用户类型',
                type: 'String'
            }, {
                caption: '数量',
                type: 'String'
            }, {
                caption: '备注',
                type: 'String'
            }, {
                caption: '电话',
                type: 'String'
            }, {
                caption: '收货地址',
                type: 'String'
            }, {
                caption: '参加时间',
                type: 'String'
            }];

            var tempRows = new Array();
            for (var i = 0; i < data.length; i++) {
                var temp = new Array();

                var partake = data[i].partake.length > 0 ? data[i].partake[0]:null;
                temp.push(partake ? data[i].community.communityName:"");
                temp.push(data[i].title ? data[i].title:"");

                if (partake && partake._doc.user && partake._doc.user._doc.nickName) {
                    temp.push(partake._doc.user._doc.nickName);
                }else {
                    temp.push("");
                }

                temp.push(partake && partake.partakeType=="1"?"APP用户":"微信用户");
                temp.push(partake && partake.number ? partake.number+"" : "");
                temp.push(partake && partake.note ? partake.note:"");
                temp.push(partake && partake.phone ? partake.phone:"");
                temp.push(partake && partake.address ? partake.address:"");
                temp.push(partake ? partake.time.getFullYear() + "-" + (partake.time.getMonth() + 1) + "-" + partake.time.getDate() + " " + partake.time.getHours() + ":" + partake.time.getMinutes():"");

                tempRows.push(temp);
            }
            conf.rows = tempRows;

            var ret = nodeExcel.execute(conf);
            res.setHeader('Content-Type', 'application/vnd.openxmlformats');
            res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
            res.end(ret, 'binary');
        }
    })
};